//
//  SubfieldTopView.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/9.
//

import UIKit

protocol SubfieldTopViewDelegate{
    
    func selectDidIndex(index: NSInteger)
}

class SubfieldTopView: UIView {
    var collectionView: UICollectionView!
    var selectIndex = 0
    var delegate: SubfieldTopViewDelegate!
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: kScreenWidth/2, height: 34)
        layout.scrollDirection = .horizontal
    
        self.collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: self.frame.size.height), collectionViewLayout: layout)
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = .white
        self.collectionView.showsVerticalScrollIndicator = false
        self.collectionView.shouldHideToolbarPlaceholder = false
        self.collectionView.register(SubfieldCollectionViewCell.self, forCellWithReuseIdentifier: "SubfieldCollectionViewCell")
        self.addSubview(self.collectionView)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension SubfieldTopView: UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubfieldCollectionViewCell", for: indexPath) as! SubfieldCollectionViewCell
        switch indexPath.row {
        case 0:
            cell.titleLab.text = MMLocalizedString("ready_stock", comment: "Ready-Stock")
        default:
            cell.titleLab.text = MMLocalizedString("pre_order", comment: "Pre-Order")
        }
        
        if self.selectIndex == indexPath.row{
            cell.titleLab.textColor = Theme.mainColor
            cell.imageView.isHidden = false
        }else{
            cell.titleLab.textColor = Theme.titleLabColor
            cell.imageView.isHidden = true
        }
        return cell
    }
    

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.selectIndex = indexPath.row
        self.collectionView.reloadData()
        self.delegate?.selectDidIndex(index: indexPath.row)
    }
    
}
